<?php

namespace App\Services;

use App\Models\AcceptRecord;
use App\Models\Project;
use App\Models\WxClient;
use App\Models\Customer;
use App\Plugins\SHH\DB;
use App\Plugins\Wechat\Client;
use Cache;
use Illuminate\Support\Facades\Auth;

class WxClientService
{
    public function initData($_user = null) {
        $user = $this->getDefaultUser($_user);
        if (is_null($user)) return [];
        // 同步联系人信息
        $projects = Project::where(['users' => $user->id])->get(['title', 'wx_id', 'plugins']);
        $project_wx = $projects->pluck('wx_id', 'id')->all();
        $wxClients = [];
        //获取到各个微信可见用户
        foreach ($project_wx as $project_id => $wx_id) {
            foreach ($wx_id as $id) {
                array_push($wxClients, $this->visibleCustomers($id, $project_id, $user));
            }
        }
        foreach ($wxClients as $id => $detail) {
            if (is_null($detail)) continue;
            //同步联系人
            $uin = $wxClients[$id]['uin'];
            $syncData = Client::syncContacts($uin);
            $userInfo = Client::getUserInfo($uin);
            $wxClients[$id]['userName'] = isset($userInfo->UserName) ? $userInfo->UserName : null;
            $wxClients[$id]['contacts'] = array_map(function($item) use ($syncData, $id) {
                $info = Customer::find($item['customer_id']);
                if ($info) {
                    $contact = $info->contactInfo($item);
                    if (isset($syncData->contacts)) {
                        // 更新UserName
                        $newUserName = $syncData->contacts->where('NickName', $contact['nickName'])->first();
                        if ($newUserName) {
                            $contact['userName'] = $newUserName['UserName'];
                        }
                    }
                    return $contact;
                } else {
                    return [
                        'cid' => $item['customer_id'],
                        'userName' => $item['userName'],
                    ];
                }
            }, $wxClients[$id]['contacts']);
        }
        $wxClients = array_values(array_filter($wxClients, function($elm) {return !is_null($elm);}));
        $project_ids = $projects->pluck('id')->all();
        $customers = [];
        foreach ($project_ids as $project_id) {
            $customerInfo = Customer::where([
                'projects.'.$project_id => [
                    '$exists' => true,
                ]
            ])->orderBy('created_at', 'desc')->get()->toArray();

            foreach ($customerInfo as $key => $customer) {
                $count = AcceptRecord::where([
                    'customers' => $customer['id'],
                    'user_id' => $user->id,
                ])->count();
                if ($count) {
                    if (!isset($customer['socialInfo'])
                    || !isset($customer['socialInfo']['wechat'])
                    || !$customer['socialInfo']['wechat']) {
                        if (!empty($customer['baseInfo']['birthday'])) {
                            $customer['baseInfo']['birthday']
                                = date('Y-m-d', $customer['baseInfo']['birthday']);
                        }
                        if (!empty($customer['baseInfo']['driverAt'])) {
                            $customer['baseInfo']['driverAt']
                                = date('Y-m-d', $customer['baseInfo']['driverAt']);
                        }
                        if (!empty($customer['socialInfo']['shihui']['regDate'])) {
                            $customer['socialInfo']['shihui']['regDate']
                                = date('Y-m-d', $customer['socialInfo']['shihui']['regDate']);
                        }
                        if(isset($customer['houseInfo'])) {
                            $customer['houseInfo'] = array_map(function ($house_info) {
                                if (!empty($house_info['最近装修时间']) && is_int($house_info['最近装修时间'])) {
                                    $house_info['最近装修时间'] = date('Y-m-d', $house_info['最近装修时间']);
                                }
                                if (!empty($house_info['租赁时间'])) {
                                    $house_info['租赁时间'][0] = date('Y-m-d', $house_info['租赁时间'][0]);
                                    $house_info['租赁时间'][1] = date('Y-m-d', $house_info['租赁时间'][1]);
                                }
                                if (isset($house_info['_id'])) {
                                    $house_info['_id'] = (string)$house_info['_id'];
                                }
                                return $house_info;
                            }, $customer['houseInfo']);
                        }
                        $customers[$customer['id']] = $customer;
                    }
                }
            }
        }
        //未审核人数
        $share = new \stdClass();
        $shh_keys = [];
        $need_check_list = config('plugin.SHH.need_checks', null);
        foreach ($projects as $project) {
            if (isset($project->plugins['shihui'])
                && isset($project->plugins['shihui']['key'])
                && (is_null($need_check_list) OR in_array($project->plugins['shihui']['key'], $need_check_list))
            ) {
                array_push($shh_keys, $project->plugins['shihui']['key']);
            }
        }
        if ($shh_keys) {
            $shh_db = DB::createDb('plugin_shh', 'customers');
            $share->wvCount = $shh_db->count([
                '_v' => 0,
                'shhKey' => ['$in' => $shh_keys],
            ]);
        }
        return compact('user', 'projects', 'wxClients' ,'customers', 'share');
    }

    public function getClientsUin($_user = null) {
        $user = $this->getDefaultUser($_user);
        $clientUins = Cache::remember("wx:ids:{$user->id}", 30, function() use ($user) {
            $projects = Project::where(['users' => $user->id])->get(['title', 'wx_id']);
            $ids = $projects->pluck('wx_id')->flatten()->all();
            return WxClient::whereIn('_id', $ids)->get()->pluck('uin')->all();
        });
        return $clientUins;
    }

    protected function getDefaultUser($_user = null) {
        return is_null($_user) ? request()->user() : $_user;
    }

    public function visibleCustomers ($wx_id, $project_id, $user) {
        $client = WxClient::find($wx_id);
        if (is_null($client)) return null;
        $wx_client = $client->toArray();
        if (isset($wx_client['contacts'])) {
            foreach ($wx_client['contacts'] as $key => $customer) {
                $accect_id = AcceptRecord::where([
                    'project_id' =>  $project_id,
                    'customers' => $customer['customer_id'],
                ])->get()
                    ->pluck('user_id')
                    ->all();
                if (!empty($accect_id) && !in_array($user->id, $accect_id)) {
                    unset($wx_client['contacts'][$key]);
                }
            }
            $wx_client['contacts'] = array_values($wx_client['contacts']);
        } else {
            $wx_client['contacts'] = [];
        }
        return $wx_client;
    }
}